package com.company.project.web;
import com.alibaba.fastjson.JSON;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.Legal;
import com.company.project.model.News;
import com.company.project.service.LegalService;
import com.company.project.util.FileUploadUtil;
import com.company.project.util.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
* Created by CodeGenerator on 2019/07/19.
*/
@RestController
@RequestMapping("/legal")
public class LegalController {
    @Resource
    private LegalService legalService;

    @Resource
    private FileUploadUtil fileUploadUtil;

    //获取法律援助分页
    @GetMapping("/list/page/{index}")
    @ResponseBody
    public Result listAll(@PathVariable(value = "index") Integer index) {
        PageUtil list = legalService.getLegalPage(index);
        return ResultGenerator.genSuccessResult(list);
    }

    //添加法律援助
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestParam String legal,@RequestParam(required = false) MultipartFile file) {
        Legal le = JSON.parseObject(legal,Legal.class);
        if (file!=null){
            String s = fileUploadUtil.writeFile(file, "other");
            if (s == null){
                return ResultGenerator.getInternalServerErrot("图片上传错误");
            }
            le.setFileUri(s);
            int i = legalService.addLegal(le);
            if (i>0){
                return ResultGenerator.genSuccessResult(true);
            }else {
                return ResultGenerator.genSuccessResult(false);
            }
        }
        int i = legalService.addLegal(le);
        if (i>0){
            return ResultGenerator.genSuccessResult(true);
        }
        return ResultGenerator.getInternalServerErrot("传输错误");
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        legalService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(Legal legal) {
        legalService.update(legal);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Legal legal = legalService.findById(id);
        return ResultGenerator.genSuccessResult(legal);
    }

    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Legal> list = legalService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


}
